#!/usr/local/bin/ruby
require 'uri'
require 'net/http'
require 'pathname'

STORE = '/store/music/952/'
BASE952 = 'http://fresh.moskva.fm/files/2011/mp4/%04d/%02d/%02d/%02d%02d.mp4'

delta2 = 180
delta3 = 300

time = Time.now - delta2
link = sprintf( BASE952, time.year, time.month, time.day, time.hour, time.min )
f1 = Pathname.new( STORE + sprintf( '%02d%02d.mp4', time.hour, time.min ) )
f2 = Pathname.new( STORE + sprintf( '%02d%02d.wav', time.hour, time.min ) )
f3 = Pathname.new( STORE + sprintf( '%02d%02d.mp3', time.hour, time.min ) )

outdated = if f3.exist? then
  if f3.mtime < Time.now - delta3 then
    true
  else
    false
  end
else
  true
end

if outdated
  puts "pathname #{f3.cleanpath} outdated"
  `/bin/rm #{f1.cleanpath}` if f1.exist?
  `/bin/rm #{f2.cleanpath}` if f2.exist?
  `/bin/rm #{f3.cleanpath}` if f3.exist?
  `/usr/bin/fetch -o #{f1.cleanpath} #{link}`
  if f1.exist? then
    `/usr/local/bin/mplayer -ss 0.085 -endpos 1:00.085 #{f1.cleanpath} -ao pcm:file=#{f2.cleanpath}`
    #`/usr/local/bin/mplayer #{f1.cleanpath} -ao pcm:file=#{f2.cleanpath}`
    if f2.exist? then
      `/usr/local/bin/lame #{f2.cleanpath} #{f3.cleanpath}`
    end
  end
  `/bin/rm #{f1.cleanpath}` if f1.exist?
  `/bin/rm #{f2.cleanpath}` if f2.exist?
end
